<template>
  <div class="home">
    <div class="detail_box">
      <!-- 菜单 -->
      <div class="tab_menu">
        <div>
          <span v-for="(item,index) in menus" :class="{'choose':index===tabIndex}" @click="chooseTab(index)">{{item}}</span>
        </div>
      </div>
      <!-- 操作 -->
      <div class="operate_box">
        <div class="item_box">
          <div class="operate_item">
            <label>关键词：</label>
            <el-input type="text" clearable placeholder="请输入关键词" v-model="keyword"></el-input>
          </div>
            <div class="operate_item">
              <label>仓库：</label>
              <el-select
                filterable
                v-model="warehouseId"
                placeholder="请选择仓库">
                <el-option
                  v-for="(item,index) in warehouseOption"
                  :key="index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>

          <div class="operate_item"  v-if="!$route.query.userId">
            <label>用户：</label>
            <userSelect @listenToUser="getUserId" :uId="user"/>
          </div>

          <div class="operate_item">
            <span class="operate_btn search_btn" @click="getTableInfo(1)">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>

        <div class="btn_box" v-if="btn&&(btn.add || btn.judgeAddr)">
          <span v-if="btn&&btn.add" class="operate_btn search_btn" @click="openPopup('',1)">新增</span>
          <span class="operate_btn export_btn" v-if="btn&&btn.judgeAddr" @click="checkAddress">同步地址</span>
        </div>

      </div>
      <!-- 表格 -->
      <div class="table_box">
        <el-table
          border
          v-loading="loading"
          :header-cell-style="tableHeader"
          ref="multipleTable"
          :data="tableInfo"
          tooltip-effect="dark"
          style="width: 100%;">
          <el-table-column
            width="80"
            prop="id"
            label="ID">
          </el-table-column>
          <el-table-column
            width="100"
            prop="userId"
            label="用户ID">
          </el-table-column>
          <el-table-column
            width="160"
            prop="userName"
            label="用户名">
            <template slot-scope="scope">{{scope.row.userName}}{{scope.row.remark ? `(${scope.row.remark})` :''}}</template>
          </el-table-column>
          <el-table-column
            width="150"
            prop="name"
            label="收货人">
            <template slot-scope="scope"><p>
              {{ scope.row.name ? scope.row.name : '——' }}</p></template>
          </el-table-column>
          <el-table-column
            prop="phone"
            width="110"
            label="联系方式">
            <template slot-scope="scope">
              <span class="change_info" @click="openPopup(scope.row.id,3,0)" v-if="btn.view&&scope.row.phone">{{scope.row.phone}}</span>
              <span v-else>——</span>
            </template>
          </el-table-column>
          <el-table-column
            width="250"
            prop="address"
            label="收货地址">
          </el-table-column>
          <el-table-column
            width="180"
            label="关联仓库"
            prop="warehouseName">
          </el-table-column>
          <el-table-column
            width="150"
            label="绑定配送员"
            prop="senderName">
            <template slot-scope="scope"><p>
              {{ scope.row.senderName ? scope.row.senderName : '——' }}</p></template>
          </el-table-column>
          <el-table-column
            width="80"
            prop="sendNum"
            label="默认数">
            <template slot-scope="scope">{{scope.row.sendNum?scope.row.sendNum:0}}</template>
          </el-table-column>
          <el-table-column
            width="90"
            label="是否默认">
            <template slot-scope="scope">{{scope.row.isDefault===1?'是':'否'}} </template>
          </el-table-column>
          <el-table-column
            width="90"
            label="状态">
            <template slot-scope="scope">
              <div :style="'color:'+(scope.row.warehouseEnable===1?'#67c430':'orange')">
                {{scope.row.warehouseEnable===1?'已审核':'待审核'}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            width="160"
            sortable
            prop="modifyTime"
            label="修改时间">
            <template slot-scope="scope">{{formatTime(scope.row.modifyTime)}}</template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            v-if="btn&&(btn.update||btn.delete||btn.updateWareHouse||btn.check||btn.view || btn.bindSender || btn.checkCenter)"
            width="200">
            <template slot-scope="scope">
              <div class="table_btn">
                <span class="change_info" @click="openPopup(scope.row.id,3,0,scope.row)" v-if="btn.view">详情</span>
                <span class="change_info" @click="openPopup(scope.row.id,1,'',scope.row)" v-if="btn.update">修改</span>
                <span @click="correctAddress(scope.row)" class="change_info" v-if="btn.checkCenter">矫正经纬度</span>
                <span class="change_info check_btn" @click="openPopup(scope.row.id,3,1)" v-if="btn.check&&scope.row.warehouseEnable===0" >审核</span>
                <span class="change_info delete_btn" @click="deleteItem(scope.row)" v-if="btn.delete">删除</span>
                <span class="change_info" @click="openPopup(scope.row.id,2)" v-if="btn.updateWareHouse">关联仓库</span>
                <span class="change_info" @click="bindSender(scope.row)" v-if="btn.bindSender">{{scope.row.senderId==0 ? '绑定配送员':'更换配送员'}}</span>
                <span class="change_info" @click="removeBind(scope.row)" v-if="btn.bindSender&&scope.row.senderId!==0">解绑配送员</span>

              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="record_page">
        <span class="page_count">共<i>{{totals}}</i>条</span>
        <el-pagination
          @size-change="sizeChange"
          @current-change="getTableInfo"
          background
          :current-page="currentPage"
          :page-sizes="[15, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next, sizes,jumper"
          :total="totals">
        </el-pagination>
      </div>
    </div>

    <edit v-if="isPop" :addressId="addressId" :remark="remark" :isOther = "isOther" @listenToChild="listenToEdit"></edit>
    <warehouse v-if="isChange" :addressId="addressId" @listenToChild="listenToEdit"></warehouse>
    <detail v-if="isDetail" :remark="remark" :addressId="addressId" :type="typeId" @listenToChild="listenToEdit"></detail>
    <bindSenderCom v-if="isBind" :addressId="addressId" :type="type" :senderId="binSenderId" :warehouseId="binWarehouseId" @listenToChild="listenToEdit"></bindSenderCom>

    <correctAddress v-if="isCorrect" :id="id"  :type="type" :name="name" :position="position" @listenToChild="listenToEdit"></correctAddress>

  </div>


</template>

<script>

import edit from "./edit";
import importData from "../../system/limit/importData";
import warehouse from "./warehouse";
import commons from "../../../utils/common";
import {bindSender, delData, listData} from "@/api/data/user/address";
import {checkAddr} from "@/api/data/address";
import detail from "./detail";
import {getBtn} from "@/utils/btnAuth";
import userSelect from '../../../components/user/index';
import {judgeRole} from "@/utils/warehouseAuth";
import bindSenderCom from './bindSender'
import correctAddress from "@/components/correctAddress/index"

export default {
  components:{
      detail,
      userSelect,
      edit,
      importData,
      warehouse,
      bindSenderCom,
      correctAddress
    },
    data() {
      return {
        menus:['未绑定配送员','已绑定配送员','待审核地址','已审核地址'],
        mIndex:0,
        user:'',
        keyword:'',
        currentPage: 1,
        pageSize: 15,
        totals: 0,
        loading: false,
        tableInfo:[],
        isPop: false,
        addressId: '',
        isChange:false,
        btn:{},
        isOther:'',
        isDetail:false,
        typeId:0,
        warehouseId:'',
        warehouseOption:[],
        // statusOption:['待审核地址','已审核地址'],
        isCheck:0,
        tabIndex:0,
        isBind:false,
        type:'',
        binSenderId:'',
        binWarehouseId:'',
        remark:'',
        id:'',
        name:'',
        position:{},
        isCorrect:false
      }
    },
    mounted() {
      this.roleHouse = judgeRole();
      this.warehouseOption = this.roleHouse.list;
      this.btn = getBtn();
      if (this.btn.query) {
        this.chooseTab(0);
      }
    },
    methods: {
      // 获取列表信息
      getTableInfo(page) {
        let that = this;
        that.loading = true;
        that.currentPage = page;
        let queryParams = {
          limit:that.pageSize,
          page:page,
          isSender:that.mIndex,
          keyword:that.keyword,
          userId:that.$route.query.userId ? parseInt(that.$route.query.userId) :that.user,
          warehouseId:that.warehouseId,
          warehouseEnable:that.isCheck
        };
        listData(queryParams).then(res => {
          that.tableInfo = res?res.list:[];
          that.totals = res?res.count:0;
          that.loading = false;
        }).catch((e) => {
          that.loading = false;
        });
      },

      // 重置
      resetTable() {
        this.pageSize = 15;
        this.keyword = '';
        this.user = '';
        // this.isCheck = '';
        this.warehouseId = '';
        this.getTableInfo(1)
      },

      //地址矫正
      correctAddress(obj) {
        console.log(obj,'啦啦啦')
        this.position = {lng:obj.lng,lat:obj.lat};
        this.name = obj.name;
        this.id = obj.id;
        this.type = 2;
        this.isCorrect = true;
      },

      //绑定配送员
      bindSender(obj) {
        obj.senderId ? this.type = 1 :this.type = 2
        // this.binSenderId = obj.senderId
        obj.senderId ? this.binSenderId = obj.senderId : this.binSenderId = ''
        this.binWarehouseId = obj.warehouseId
        this.addressId = obj.id;
        this.isBind = true
      },
      //确定审核地址
      checkAddress() {
        let that = this;
        that.$confirm('确定同步用户地址信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          checkAddr().then((res)=> {})
        }).then(()=> {
          setTimeout(()=> {
            that.$confirm('同步成功！', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
            }).catch(() => {
            });
          },500)

        }).catch(() => {
        });
      },

      chooseTab(index){
        this.tabIndex = index;
        if(index == 0 || index == 1) {
          this.isCheck = '';
          this.mIndex = index;
        }else if(index == 2 || index == 3){
          this.mIndex = '';
          index == 2 ? this.isCheck = 0 :this.isCheck = 1;
        }
        this.getTableInfo(1);
      },

      // 获取用户id
      getUserId(e){
        this.user = e;
      },

      // 删除
      deleteItem(obj) {
        let that = this;
        that.$confirm('确定删除'+obj.name+'信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return delData(obj.id);
        }).then(() => {
          that.getTableInfo(that.currentPage);
          that.$message.success({
            message:'删除成功！',
            duration:1500
          });
        }).catch(() => {
          // console.product('fail')
        });
      },

      // 解绑配送员
      removeBind(obj) {
        let that = this;
        that.$confirm('确定解绑'+obj.name+'配送员?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            id:obj.id,
            senderId:0
          }
          return bindSender(params);
        }).then(() => {
          that.getTableInfo(that.currentPage);
          that.$message.success({
            message:'解绑成功！',
            duration:1500
          });
        }).catch(() => {
          // console.product('fail')
        });
      },

      // 打开弹窗
      openPopup(id,type,operate,obj) {
        if(obj) {
          this.remark = obj.remark
        }
        this.typeId = operate;
        type===1?this.isPop = true:(type===2?this.isChange = true:this.isDetail = true);
        this.addressId = '';
        if(id) {
          this.addressId = id;
          this.isOther = undefined;
        }else if(this.user) {
          this.isOther = 1;
          this.addressId = this.user;
        }
      },

      listenToEdit(e){
        this.isPop = false;
        this.isChange = false;
        this.isDetail = false;
        this.isBind = false;
        this.isCorrect = false;
        if (e.refresh){
          this.getTableInfo(this.currentPage)
        }
      },

      formatTime(time){
        return commons.formatTime(time)
      },

      sizeChange(val){
        this.pageSize =val;
        this.getTableInfo(1)
      },

      // 设置table标题居中
      tableHeader({row, column, rowIndex, columnIndex}) {
        return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600'
      },
    }
  }
</script>

<style scoped>
.detail_box{
  padding-top: 10px;
}
.check_btn {
  color: #f7ab20;
}


</style>
